<?php
/***************************************************************
 *  Copyright notice
 *
 *  (c) 2011 Gerhard Kollinger <gerhard@kollinger.it>
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 * Hint: use extdeveval to insert/update function index above.
 */

require_once(PATH_tslib.'class.tslib_pibase.php');

/**
 * Replacer function for deprecated mysql_escape_string()
 *
 * @param $unescaped_string
 * @return string
 */
function mysql_escape_string_replace($unescaped_string) {
    /** @noinspection PhpDeprecationInspection */
    return mysql_escape_string($unescaped_string);
}


/**
 * Plugin 'Listview of Events' for the 'gk_eisview' extension.
 *
 * @author        Gerhard Kollinger <gerhard@kollinger.it>
 * @package       TYPO3
 * @subpackage    tx_gkeisview
 */
class tx_gkeisview_pi3 extends tslib_pibase {
    var $prefixId = 'tx_gkeisview_pi3'; // Same as class name
    var $scriptRelPath = 'pi3/class.tx_gkeisview_pi3.php'; // Path to this script relative to the extension dir.
    var $extKey = 'gk_eisview'; // The extension key.
    var $pi_checkCHash = TRUE;
    private $artist_list_pid_music;
    private $artist_list_pid_discourse;
    private $actual_artist_output_order;
    private $actual_event_title = "";
    private $actual_event_title_de = "";
    private $actual_event_title_en = "";
    const MYSQL_DEBUG = FALSE;
    const MY_IP       = '84.115.177.240';
    public $templateCode;
    public $tpl_event;
    public $mysqli;
    public $event_marker_array;


    private static function silentDebug($info = NULL, $mixedOutputVar = 'no_value', $dieAfter = NULL, $htmlCommented = TRUE) {
        if($_SERVER['REMOTE_ADDR'] == self::MY_IP) {
            if($mixedOutputVar != 'no_value') {
                $output = is_array($mixedOutputVar) ? print_r($mixedOutputVar, TRUE) : $mixedOutputVar;
                $output = is_string($output) ? $output : var_export($output, TRUE);
                if($htmlCommented) {
                    echo '<!--'.$info.': '.$output.'-->'."\n";
                } else {
                    echo $info.': '.$output.'<br />'."\n";
                }
                if($dieAfter) {
                    die();
                }
            }
        }

        return;
    }

    /**
     * The main method of the PlugIn
     *
     * @param    string        $content: The PlugIn content
     * @param    array         $conf   : The PlugIn configuration
     * @return    The content that is displayed on the website
     */
    function main($content, $conf) {
        $this->pi_initPIflexForm();
        $this->conf = $conf;
        $this->pi_setPiVarDefaults();
        $this->pi_loadLL();

        $this->connectDB();

        // Template Code
        $langKey            = $GLOBALS['TSFE']->sys_language_uid == 0 ? "DE" : "EN";
        $templateFile       = $this->getTemplateName($langKey);
        $this->templateCode = $this->cObj->fileResource($templateFile);


        $content = $this->getEventList();

        return $this->pi_wrapInBaseClass($content);
    }

    function connectDB() {
        $db_params = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['gk_eisview']);

        if(empty($db_params["artist_list_pid_music"]) || empty($db_params["artist_list_pid_discourse"])) {
            die("Bitte Artist-Liste-Musik PID und Artist-Liste-Diskurs PID im Extension Manager eintragen!");
        }
        $this->artist_list_pid_music     = $db_params["artist_list_pid_music"];
        $this->artist_list_pid_discourse = $db_params["artist_list_pid_discourse"];

        $this->mysqli = new mysqli('localhost', $db_params["user"], $db_params["pass"], $db_params["database"]);
        $this->mysqli->query("SET NAMES 'utf8'");

        /*
           * Use this instead of $connect_error if you need to ensure
           * compatibility with PHP versions prior to 5.2.9 and 5.3.0.
           */
        if(mysqli_connect_error() && self::MYSQL_DEBUG) {
            die('Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
        }
    }

    function getEventList() {
        $tpl_main        = $this->cObj->getSubpart($this->templateCode, '###EVENT_LIST_VIEW###');
        $this->tpl_event = $this->cObj->getSubpart($tpl_main, '###EVENT###');
        $subparts        = array();

        $event_day_array      = explode(",", $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'eventday'));
        $event_location_array = explode(",", $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'eventlocation'));
        $event_id             = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'eventname');
        $event_cat            = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'category');
        $event_sub_cat_array  = explode(",", $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'subcategory'));
        $rendering            = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'rendering');

        if($rendering == "location") {
            // Event optimiert
            $link_pids = explode(",", $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'locationlinkpids'));
            $i         = 0;

            $appearance = "";

            $query        = $this->getQueryEventRendered($event_day_array, $event_location_array, $event_cat, $event_sub_cat_array);
            $result_array = $this->getQueryResultArray($query);

            foreach($result_array as $event_array) {
                if(isset($link_pids[$i])) {
                    $actual_link_page_id = $link_pids[$i];

                    $link                                   = $this->pi_getPageLink($actual_link_page_id);
                    $event_array["event_url_from_flexform"] = $link;
                }
                $i ++;

                if(isset($event_array["typoid"])) {
                    $actual_link_page_id = $event_array["typoid"];

                    $link                     = $this->pi_getPageLink($actual_link_page_id);
                    $event_array["event_url"] = $link;
                }


                //wird zwar nur einmal benötigt, ist aber nicht anders zu holen
                $this->event_marker_array = $this->getMarker($event_array, "view_event_light", "view_event_appearance_", FALSE, FALSE, "get_event_list_a");
                $event_subpart_array      = $this->getSubparts($event_array, "view_event_appearance_");

                $appearance .= $this->fillEventAppearancesSubpart($event_array);
            }
            $event_subpart_array["###appearance###"] = $appearance;

            $subparts["###EVENT###"] = $this->cObj->substituteMarkerArrayCached($this->tpl_event, $this->event_marker_array, $event_subpart_array);
        } else {
            // Artist optimiert

            $subparts["###EVENT###"] = "";

            // get events
            $query        = $this->getQuery($event_day_array, $event_location_array, $event_id, $event_cat, $event_sub_cat_array);
            $result_array = $this->getQueryResultArray($query);

            foreach($result_array as $event_array) {
                // add event links to $event_array (we could loop event links in special subpart, but this handling is as it was expected at the beginning)
                $different_link_types = $this->getQueryResultArray('select DISTINCT(link_type_code) from view_event_detail_links');
                foreach($different_link_types as $link_type) {
                    // first set all possible link types to provide empty subpart handling in FE
                    for($i = 1; $i <= 5; $i++) {
                        if($i == 1) {
                            $event_array['link_'.$link_type['link_type_code']]          = '';
                            $event_array['link_'.$link_type['link_type_code'].'_descr'] = '';

                            // unset these old links from db
                            /*
                            unset($event_array['link_'.$link_type['link_type_code'].'_'.$i]);
                            unset($event_array['link_'.$link_type['link_type_code'].'_'.$i.'_descr']);
                            unset($event_array['link_'.$link_type['link_type_code'].$i]);
                            unset($event_array['link_'.$link_type['link_type_code'].$i.'_descr']);
                            */
                        } else {
                            $event_array['link_'.$link_type['link_type_code'].'_'.$i]          = '';
                            $event_array['link_'.$link_type['link_type_code'].'_'.$i.'_descr'] = '';

                            // unset these old links from db
                            /*
                            unset($event_array['link_'.$link_type['link_type_code'].$i]);
                            unset($event_array['link_'.$link_type['link_type_code'].$i.'_descr']);
                            */
                        }

                    }
                }

                // now add existing link types
                $query       = "select * from view_event_detail_links where event_id = '".$event_array['event_id']."' order by link_priority ASC";
                $event_links = $this->getQueryResultArray($query);
                $link_amount = array();

                foreach($event_links as $event_link) {
                    if( ! $link_amount[$event_link['link_type_code']]) {
                        $event_array['link_'.$event_link['link_type_code']]          = $event_link['link_url'];
                        $event_array['link_'.$event_link['link_type_code'].'_descr'] = $event_link['link_description'];
                        $link_amount[$event_link['link_type_code']] = 1;
                    } else {
                        $link_amount[$event_link['link_type_code']]++;
                        $event_array['link_'.$event_link['link_type_code']."_".$link_amount[$event_link['link_type_code']]]          = $event_link['link_url'];
                        $event_array['link_'.$event_link['link_type_code']."_".$link_amount[$event_link['link_type_code']].'_descr'] = $event_link['link_description'];
                    }
                }

                $this->event_marker_array = $this->getMarker($event_array, "view_event_light", "view_event_", FALSE, FALSE, "get_event_list_b");
                $event_subpart_array      = $this->getSubparts($event_array);
                $event_id                 = $event_array["event_id"];

                // get artists for event
                $event_subpart_array["###appearance###"] = $this->fillArtistAppearancesSubpart($event_id);
                $this->actual_artist_output_order        = "";

                $subparts["###EVENT###"] .= $this->cObj->substituteMarkerArrayCached($this->tpl_event, $this->event_marker_array, $event_subpart_array);
            }
        }

        return $this->cObj->substituteMarkerArrayCached($tpl_main, array(), $subparts);
    }

    private function fillEventAppearancesSubpart($event_array) {
        $appearance_marker_array  = $this->getMarker($event_array, "view_event_light", "view_event_appearance_", FALSE, FALSE, "fillEventAppearancesSubpart");
        $appearance_subpart_array = $this->getSubparts($event_array, "view_event_appearance_");

        $tpl_appearance     = $this->cObj->getSubpart($this->tpl_event, "###appearance###");
        $appearance_content = $this->cObj->substituteMarkerArrayCached($tpl_appearance, $appearance_marker_array, $appearance_subpart_array);

        return $appearance_content;
    }

    private function fillArtistAppearancesSubpart($event_id) {
        $query        = "SELECT * FROM view_event_appearance WHERE view_event_appearance.event_id = '".$event_id."' order by view_event_appearance.output_order asc";
        $result_array = $this->getQueryResultArray($query);

        $result_array_count = count($result_array);

        $appearance_content = "";
        for($i = 0; $i < $result_array_count; $i ++) {
            $appearance_array  = $result_array[$i];
            $output_order      = $result_array[$i]["output_order"];
            $next_output_order = $result_array[$i + 1]["output_order"];

            if($output_order == $next_output_order) {
                $multiple_artists_in_line = TRUE;
            } else {
                $multiple_artists_in_line = FALSE;
            }

            $appearance_marker_array  = $this->getMarker($appearance_array, "view_event_appearance", "view_event_appearance_", TRUE, $multiple_artists_in_line, "fillArtistAppearancesSubpart");
            $appearance_subpart_array = $this->getSubparts($appearance_array, "view_event_appearance_");


            $tpl_appearance = $this->cObj->getSubpart($this->tpl_event, "###appearance###");
            $appearance_content .= $this->cObj->substituteMarkerArrayCached($tpl_appearance, $appearance_marker_array, $appearance_subpart_array);
        }

        return $appearance_content;
    }

    private function getQueryResultArray($query) {//echo("<!--Query:".$query."-->\n\n");
        $query   = preg_replace_callback("#( '|\(')(.*)(' |'\)|\\n|\n|\\n\\r|\n\r|\\r\\n|\r\n)#U", "tx_gkeisview_pi3::mysql_escape_string_for_replace", $query);
        $results = $this->mysqli->query($query);


        if($this->mysqli->error != "" && self::MYSQL_DEBUG) {
            die("Mysql Error: ".$this->mysqli->error."<br><br>"."Betroffener Query: ".$query);
        }

        $result_array = array();
        while($result = $results->fetch_assoc()) {
            array_push($result_array, $result);
        }
        $results->close();

        return $result_array;
    }

    static function mysql_escape_string_for_replace($matches) {
        /** @noinspection PhpDeprecationInspection */
        return $matches[1].mysql_escape_string_replace($matches[2]).$matches[3];
    }

    function getQueryEventRendered($event_day_array, $event_location_array, $event_cat, $event_sub_cat_array) {
        if(array_search("all_this_year", $event_day_array) !== FALSE) {
            // Immer nur ein Datum und eine Location, da sonst ein enormer Sriptaufwand in Bezug auf Datenbankabragen entstehen würde
            die('Veranstaltunstag-Auswahl: "Alle heuer" nicht erlaubt bei Location optimiertenm Rendering!');
        } else if(array_search("all", $event_day_array) !== FALSE) {
            die('Veranstaltunstag-Auswahl: "Alle" nicht erlaubt bei Event optimiertem Rendering!');
        } else {
            $event_day_query = "date_name = '".$event_day_array[0]."' and ";
        }

        if(array_search("all", $event_location_array) !== FALSE || array_search("", $event_location_array) !== FALSE) {
            die('Veranstaltunsort-Auswahl: "Alle" nicht erlaubt bei Event optimiertem Rendering!');
        } else {
            $event_location_query = "location_name = '".$event_location_array[0]."' and ";
        }

        if($event_cat != "all") {
            $event_cat_query = "cat_type like '%".$event_cat."%' and ";
        } else {
            $event_cat_query = "cat_type like '%' and ";
        }

        if(array_search("all", $event_sub_cat_array) !== FALSE || array_search("", $event_sub_cat_array) !== FALSE) {
            $event_sub_cat_query = "cat_type2 like '%'";
        } else {
            $event_sub_cat_query = "(";
            foreach($event_sub_cat_array as $event_sub_cat) {
                $event_sub_cat_query .= "cat_type2 like '%".$event_sub_cat."%' or ";
            }
            $event_sub_cat_query = substr($event_sub_cat_query, 0, - 4);
            $event_sub_cat_query .= ") ";
        }

        // view_event_light weil es sich hier um eine übersicht handelt bei der keine event_links benötigt werden
        $query = "SELECT DISTINCT title, title_en, typoid, location_name, cat_type, cat_type2, cat_types_list, is_livemedia, language, time_begin, time_end, date_name
				  FROM view_event_light
   				  WHERE ".$event_day_query.$event_location_query.$event_cat_query.$event_sub_cat_query."ORDER BY time_begin ASC";

        return $query;
    }

    function getQuery($event_day_array, $event_location_array, $event_id, $event_cat, $event_sub_cat_array) {
        if($event_id != "all") {
            $query = "select * from view_event where event_id = '".$event_id."'";

            return $query;
        }


        if(array_search("all_this_year", $event_day_array) !== FALSE) {
            $event_day_query = "date_name like '%".date("Y")."%' and ";
        } else if(array_search("all", $event_day_array) !== FALSE | array_search("", $event_day_array) !== FALSE) {
            $event_day_query = "date_name like '%' and ";
        } else {
            $event_day_query = "(";
            foreach($event_day_array as $event_day) {
                $event_day_query .= "date_name = '".$event_day."' or ";
            }
            $event_day_query = substr($event_day_query, 0, - 4);
            $event_day_query .= ") and ";
        }


        if(array_search("all", $event_location_array) !== FALSE || array_search("", $event_location_array) !== FALSE) {
            $event_location_query = "location_name like '%' and ";
        } else {
            $event_location_query = "(";
            foreach($event_location_array as $event_location) {
                $event_location_query .= "location_name = '".$event_location."' or ";
            }
            $event_location_query = substr($event_location_query, 0, - 4);
            $event_location_query .= ") and ";
        }


        if($event_cat != "all") {
            $event_cat_query = "cat_type like '%".$event_cat."%' and ";
        } else {
            $event_cat_query = "cat_type like '%' and ";
        }


        if(array_search("all", $event_sub_cat_array) !== FALSE || array_search("", $event_sub_cat_array) !== FALSE) {
            $event_sub_cat_query = "cat_type2 like '%' ";
        } else {
            $event_sub_cat_query = "(";
            foreach($event_sub_cat_array as $event_sub_cat) {
                $event_sub_cat_query .= "cat_type2 like '%".$event_sub_cat."%' or ";
            }
            $event_sub_cat_query = substr($event_sub_cat_query, 0, - 4);
            $event_sub_cat_query .= ") ";
        }

        $query = "select * from view_event_light where ".$event_day_query.$event_location_query.$event_cat_query.$event_sub_cat_query."order by date_date asc, location_order asc, time_begin asc";

        return $query;
    }

    function getMarker($input_array, $table = "", $marker_prefix = "view_event_", $getArtistLinks = FALSE, $multiple_artists_in_line = FALSE, $trigger = "not given") {
        $marker_array                = array();
        $marker_array["###table###"] = $table;
        $rendering                   = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'rendering');

        foreach($input_array as $key => $value) {
            if(empty($value) && $value != "0" || $value == "<br>") {
                $value = $this->conf["event-list_zero-value"];

                if($key == "title_en") {
                    $value = $input_array["title"];
                } elseif($key == "sub_title_en") {
                    $value = $input_array["sub_title"];
                }
            }

            $marker_array["###".$marker_prefix.$key."###"] = trim($value);


            if($key == "date_date") {
                $marker_array["###de_datum_kurz###"] = $this->getFormattedDate($value);
                $marker_array["###de_datum_lang###"] = $this->getFormattedDate($value, FALSE);
                $marker_array["###en_datum_kurz###"] = $this->getFormattedDate($value, TRUE, "en");
                $marker_array["###en_datum_lang###"] = $this->getFormattedDate($value, FALSE, "en");
            }

            // extract youtube video id
            if(preg_match("#video#", $key)) {
                if(preg_match("#v=([^&]+)#", $value, $player_id_matches)) {
                    if(isset($player_id_matches[1])) {
                        $marker_array["###".$marker_prefix.$key."_player_id###"] = $player_id_matches[1];
                    }
                } elseif(preg_match("#vimeo#", $value)) {
                    $slashExplodedVimeoLink = explode('/', $value);
                    $marker_array["###".$marker_prefix.$key."_player_id###"] = $slashExplodedVimeoLink[count($slashExplodedVimeoLink) - 1];
                    $marker_array["###".$marker_prefix."vimeo_id_1###"]     = $marker_array["###".$marker_prefix.$key."_player_id###"]; //overite existing one used marker
                }
            }
        }


        # title die gleich und untereinander sind: nur ersten anzeigen
        if($rendering != "location" && ! $getArtistLinks) {
            if(isset($marker_array["###".$marker_prefix."title_de"."###"])) {
                if($marker_array["###".$marker_prefix."title_de"."###"] == $this->actual_event_title_de) {
                    $marker_array["###".$marker_prefix."title_de"."###"] = "";
                }

                $this->actual_event_title_de = trim($input_array["title_de"]);
            }

            if(isset($marker_array["###".$marker_prefix."title_en"."###"])) {
                if($marker_array["###".$marker_prefix."title_en"."###"] == $this->actual_event_title_en) {
                    $marker_array["###".$marker_prefix."title_en"."###"] = "";
                }

                $this->actual_event_title_en = trim($input_array["title_en"]);
            }

            if(isset($marker_array["###".$marker_prefix."title"."###"])) {
                if($marker_array["###".$marker_prefix."title"."###"] == $this->actual_event_title) {
                    $marker_array["###".$marker_prefix."title"."###"] = "";
                }

                $this->actual_event_title = trim($input_array["title"]);
            }
        }


        if(isset($marker_array["###".$marker_prefix."cat_type2"."###"])) {
            $marker_array["###".$marker_prefix."cat_type2"."###"] = $this->getCorrectCategoryName($marker_array["###".$marker_prefix."cat_type2"."###"]);
            $cat_type_array                                       = explode(",", $marker_array["###".$marker_prefix."cat_type2"."###"]);

            for($i = 0; $i < 11; $i ++) {
                $value                                  = $cat_type_array[$i];
                $value                                  = $value == "" ? "none" : $value;
                $marker_array["###cat_type2_".$i."###"] = $value;
            }
        }

        if($getArtistLinks) {
            $this->prefixId   = preg_replace("#3#", "1", $this->prefixId);
            $artist_list_pid  = $input_array["artist_cat_type"] == "art" ? $this->artist_list_pid_music : $this->artist_list_pid_discourse;
            $addurlParameters = array();
            if($input_array["artist_cat_type"] == "discourse") {
                $addurlParameters['guest'] = $input_array["url_shortcode"];
            } else {
                if(isset($input_array["artist_cat_type"])) {
                    $addurlParameters['artist'] = $input_array["url_shortcode"];
                } else {
                    if($input_array["cat_type"] == "discourse") {
                        $addurlParameters['guest'] = $input_array["url_shortcode"];
                    } else {
                        $addurlParameters['artist'] = $input_array["url_shortcode"];
                    }
                }
            }
            $link                             = $this->pi_linkTP_keepPIvars_url($addurlParameters, TRUE, FALSE, $artist_list_pid);
            $marker_array["###artist_url###"] = preg_replace("#///#", "/", $link);
            $this->prefixId                   = preg_replace("#1#", "3", $this->prefixId);

            // Artists nebeneinander
            if($multiple_artists_in_line) {
                $query = "SELECT artist_id,
								 artist_cat_type, 
								 artist_name, 
								 label_1, 
								 label_2, 
								 label_3, 
								 country_code, 
								 is_livemedia,
								 appearance_type_list,
								 url_shortcode
						  FROM view_event_appearance 						
						  WHERE 
						  output_order = '".$input_array["output_order"]."' AND 
						  date_date = '".$input_array["date_date"]."' AND
						  event_id = '".$input_array["event_id"]."' 
						  order by artist_name asc";

                $artist_id_array = $this->getQueryResultArray($query);

                $marker_array["###artist_names_with_links###"] = "";

                $i = 0;
                foreach($artist_id_array as $artist) {
                    $i ++;
                    if($i == 1) {
                        $marker_array["###artist_names_with_links###"] .= $this->getArtistNamesWithLinks($artist, TRUE);
                    } else {
                        $marker_array["###artist_names_with_links###"] .= $this->getArtistNamesWithLinks($artist);
                    }
                }
            } else {
                $marker_array["###artist_names_with_links###"] = $this->getArtistNamesWithLinks($input_array, TRUE);
            }
        }

        # damit nicht 2mal die gleichen artists angezeigt werden
        if($this->actual_artist_output_order == $input_array["output_order"]) {
            $marker_array["###artist_names_with_links###"] = "";
        }

        $this->actual_artist_output_order = $input_array["output_order"];

        $marker_array['trigger'] = $trigger;
        $marker_array["###markers###"] = print_r($marker_array, TRUE);

        return $marker_array;
    }

    function getCorrectCategoryName($category) {
        if($GLOBALS['TSFE']->sys_language_uid == 0) {
            $de_names = array("#discussion#", "#workshop#", "#video-stream#", "#lecture#", "#film#", "#A/V#", "#music#", "#Q+A#", "#visuals#", "#literature#", "#installation#", "#performance#",);

            $en_names = array("Diskussion", "Workshop", "Video-Stream", "Vortrag", "Film", "A/V", "Musik", "Q&A", "Visuals", "Literatur", "Installation", "Performance",);

            $category = preg_replace($de_names, $en_names, $category);
        }

        return $category;
    }

    function getArtistNamesWithLinks($artist, $first = FALSE) {
        // Damit die richtige url entsteht und nur 1 cache eintrag geschrieben wird
        $this->prefixId = preg_replace("#3#", "1", $this->prefixId);

        $artist_list_pid = $artist["artist_cat_type"] == "art" ? $this->artist_list_pid_music : $this->artist_list_pid_discourse;

        $label_1_string = $artist["label_1"] != "" ? '<span class="label">'.$artist["label_1"].',</span>' : "";
        $label_2_string = $artist["label_2"] != "" ? '<span class="label">'.$artist["label_2"].',</span>' : "";
        $label_3_string = $artist["label_3"] != "" ? '<span class="label">'.$artist["label_3"].'</span>' : "";

        if($label_2_string == "") {
            $label_1_string = preg_replace("#,#", "", $label_1_string);
        } else if($label_3_string == "") {
            $label_2_string = preg_replace("#,#", "", $label_2_string);
        }

        if(empty($label_1_string) && empty($label_2_string) && empty($label_3_string)) {
            $slash = "";
        } else {
            $slash = "/";
        }

        $country_string            = '<span class="country_code">'.$slash.$artist["country_code"].'</span>';
        $label_country_code_string = $label_1_string.$label_2_string.$label_3_string.$country_string;


        $addurlParameters = array();
        if($artist["artist_cat_type"] == "discourse") {
            $addurlParameters['guest'] = $artist["url_shortcode"];
        } else {
            if(isset($artist["artist_cat_type"])) {
                $addurlParameters['artist'] = $artist["url_shortcode"];
            } else {
                if($artist["cat_type"] == "discourse") {
                    $addurlParameters['guest'] = $artist["url_shortcode"];
                } else {
                    $addurlParameters['artist'] = $artist["url_shortcode"];
                }
            }
        }
        $link = $this->pi_linkTP_keepPIvars_url($addurlParameters, TRUE, FALSE, $artist_list_pid);

        $visual_installation_string = "";
        if($artist["appearance_type_list"] != "") {
            $app_type                   = $artist["appearance_type_list"];
            $live_av_string             = "";

            if(preg_match("#live#i", $app_type)) {
                $live_av_string .= "live ";
            }

            if(preg_match("#A/V#i", $app_type)) {
                $live_av_string .= "a/v";
            }

            $live_av_string = $live_av_string == " - " ? "" : $live_av_string;


            if($first) {
                if(preg_match("#visuals#i", $app_type)) {
                    $visual_installation_string .= "visuals";
                }

                if(preg_match("#installation#i", $app_type)) {
                    $visual_installation_string .= $visual_installation_string == "" ? "installation" : " / installation";
                }
            }
            $visual_installation_string .= $visual_installation_string == "" ? "" : ": ";

            $visual_installation_string = $visual_installation_string == "" ? "" : '<span class="seppi">'.$visual_installation_string."</span>";
            $live_av_string             = $live_av_string == "" ? "" : '<span class="seppi">'.$live_av_string."</span>";
        }

        $artistNamesWithLinks = $visual_installation_string.'<a href="'.$link.'" target="_self">'.$artist["artist_name"]."</a>".$live_av_string.' <span class="label">('.$label_country_code_string.')</span>';

        $this->prefixId = preg_replace("#1#", "3", $this->prefixId);

        return $artistNamesWithLinks;
    }

    function getSubparts($event_array, $marker_prefix = "view_event_") {
        $event_subpart_array = array();

        foreach($event_array as $key => $value) {
            if(empty($value) && $value != "0" || $value == "<br>") {
                $event_subpart_array["###".$marker_prefix.$key."_subpart###"] = "";
            } else {
                $tpl_event_subpart = $this->cObj->getSubpart($this->tpl_event, "###view_event_".$key."_subpart###");

                $event_subpart_array["###".$marker_prefix.$key."_subpart####"] = $this->cObj->substituteMarkerArrayCached($tpl_event_subpart, $this->event_marker_array, array());
            }
        }

        return $event_subpart_array;
    }

    function getFormattedDate($date_date_from_db, $short = TRUE, $lang = "de") {
        $date_array = explode("-", $date_date_from_db);

        if(count($date_array) == 3) {
            $timestamp = mktime(0, 0, 0, $date_array[1], $date_array[2], $date_array[0]);
        } else {
            return;
        }

        /*
               if($lang == "de")
               {
                   setlocale(LC_TIME, "de_DE");

                   if($short)
                   {
                       $format = "%a. %d %b";
                   }
                   else
                   {
                       $format = "%A, %d %b";
                   }
               }
               else
               {
                   setlocale(LC_TIME, "en_US");
               }

               return strftime($format, $timestamp);
        */

        if($short) {
            $format = "D. d M";
        } else {
            $format = "l, d M";
        }

        $date = date($format, $timestamp);

        if($lang == "de") {
            $de_names = array("Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag", "Mo", "Di", "Mi", "Do", "Fr", "Sa", "So", "Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez", "Montag",);

            $en_names = array("#Monday#", "#Tuesday#", "#Wednesday#", "#Thursday#", "#Friday#", "#Saturday#", "#Sunday#", "#Mon#", "#Tue#", "#Wed#", "#Thu#", "#Fri#", "#Sat#", "#Sun#", "#Jan#", "#Feb#", "#Mar#", "#Apr#", "#May#", "#Jun#", "#Jul#", "#Aug#", "#Sep#", "#Oct#", "#Nov#", "#Dec#", "#Motag#",);

            $date = preg_replace($en_names, $de_names, $date);
        }

        return $date;
    }

    /**
     * Get multilanguage template
     *
     * @param    integer        $language: Language
     * @return    string        $t_name: Template
     **/
    function getTemplateName($language) {

        if($this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'eventname') == "all") {
            $event_cat = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'category');
            $rendering = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'rendering');

            if($rendering == "location") {
                if($event_cat == "discourse") {
                    $t_type = "list-location_rendered-discourse";
                } else {
                    $t_type = "list-location_rendered";
                }
            } else {
                if($event_cat == "discourse") {
                    $t_type = "list-discourse";
                } else {
                    $t_type = "list";
                }
            }
        } else {
            $event_id = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'eventname');

            $temp_event_cat_type     = $this->getQueryResultArray("select cat_type from view_event where event_id = ".$event_id);
            $event_cat_type_flexform = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'category');
            $event_cat_type          = $temp_event_cat_type[0]["cat_type"];

            if($event_cat_type_flexform != "all" || $event_cat_type_flexform != "") {
                $event_cat_type = $event_cat_type_flexform;
            }

            if($event_cat_type == "discourse") {
                $t_type = "detail-discourse";
            } else {
                $t_type = "detail";
            }
        }

        $t_name            = $this->conf["template_folder_event-list"].$language.$this->conf["template_name_event-".$t_type];
        $standard_template = $this->conf["template_folder_event-list"]."DE".$this->conf["template_name_event-".$t_type];

        if(file_exists($t_name))
            return ($t_name); else if(file_exists($standard_template))
            return ($standard_template); else die ("<p align=center>"."Template: <b>".$t_name."</b> nicht gefunden!</p>");
    }

    function __destruct() {
        $this->mysqli->close();
    }
}


if(defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/gk_eisview/pi3/class.tx_gkeisview_pi3.php']) {
    include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/gk_eisview/pi3/class.tx_gkeisview_pi3.php']);
}

?>